import '../global.css';
import { Slot, useRouter, useSegments } from 'expo-router';
import { AuthProvider, useAuth } from '../utils/auth/authContext';
import { useEffect } from 'react';

// 认证保护组件
function AuthGuard() {
  const { isAuthenticated, isLoading } = useAuth();
  const segments = useSegments();
  const router = useRouter();
  
  useEffect(() => {
    // 登录页面路径
    const loginScreens = ['/login', '/(auth)/login'];
    const inAuthGroup = segments[0] === '(auth)' || loginScreens.includes('/' + segments.join('/'));
    
    if (!isLoading) {
      // 如果用户未登录且不在认证组内，重定向到登录页面
      if (!isAuthenticated && !inAuthGroup) {
        router.replace('/login');
      } else if (isAuthenticated && inAuthGroup) {
        // 如果用户已登录且在认证组内，重定向到首页
        router.replace('/');
      }
    }
  }, [isAuthenticated, isLoading, segments, router]);
  
  return <Slot />;
}

// 根布局组件
export default function RootLayout() {
  return (
    <AuthProvider>
      <AuthGuard />
    </AuthProvider>
  );
}
